package com.ruoyi.web.controller.system;


import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.framework.web.service.MobileLoginService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.LoginParams;
import com.ruoyi.system.domain.utils.SMSUtils;
import com.ruoyi.system.domain.utils.ValidateCodeUtils;
import com.ruoyi.system.domain.vo.UserAgentInterceptor;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.core.config.GeTuiUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

import static com.ruoyi.common.utils.SecurityUtils.getLoginUser;

/**
 * 登录控制器
 *
 * @author SK
 * @since 2018/6/13
 */
@RestController
@SessionAttributes("user")
@RequestMapping("/mobile/login")
public class LoginController{

    @Autowired(required = false)
    private TokenService tokenService;

    @Autowired(required = false)
    private MobileLoginService loginService;

//
//    @Autowired
//    private ServerConfig serverConfig;

    @Autowired
    private ISysUserService userService;


    /**
     * 会员登录
     * @return -1 用户名或密码错误  -2 账号冻结  -3 账号锁定 1 成功  -4 验证码错误
     */
    @PostMapping("/loginByPassword")
    @ResponseBody
    public AjaxResult loginByPassword(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String phoneNo = request.getParameter("phoneNo");
        String validCode = request.getParameter("validCode");
        String loginType = request.getParameter("loginType");
        String userAgent = request.getHeader("User-Agent");
        String cid = request.getParameter("cid");
        UserAgentInterceptor.setUserAgent(userAgent);
        // 登录结果
        LoginParams loginParams = new LoginParams();
        loginParams.setUsername(username);
        loginParams.setPassword(password);
        loginParams.setPhoneNo(phoneNo);
        loginParams.setValidCode(validCode);
        loginParams.setLoginType(loginType);
        loginParams.setCid(cid);

        return loginService.login(loginParams);
    }


    /**
     * 发送验证码
     */
    @PostMapping("/sendCode")
    @ResponseBody
    public AjaxResult sendRegisterCode(HttpServletRequest request) throws Exception {

        String phoneNo = request.getParameter("phoneNo");
        String codeType = request.getParameter("codeType");
        String validCode = ValidateCodeUtils.generateValidateCode(
                6
        );
        // 登录结果
        LoginParams loginParams = new LoginParams();
        loginParams.setPhoneNo(phoneNo);
        loginParams.setValidCodeType(codeType);
        loginParams.setValidCode(validCode);
        return loginService.sendCode(loginParams);
    }

    /**
     * 图片上传
     */
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult uploadphoto(MultipartFile file,HttpServletRequest request) throws Exception {
                // 上传文件路径String
//        try{
//        String filePath = RuoYiConfig.getUploadPath();
//
//        // 上传并返回新文件名称
//        String fileName = FileUploadUtils.upload(filePath, file);
//        String url=serverConfig.getUrl()+ fileName;
//        AjaxResult ajax= AjaxResult.success();
//        ajax.put( "url", url);
//        ajax.put( "fileName" , fileName);
//        ajax.put( "newFileName" , FileUtils.getName(fileName));
//            ajax.put( "originalFilename",file.getOrigin   alFilename());
//        return ajax;
//        }
//        catch(Exception e) {
//            return AjaxResult.error(e.getMessage());
//        }
        String phoneNo = request.getParameter("phonenumber");





        if (!file.isEmpty())
        {
            String avatar = FileUploadUtils.upload(RuoYiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            if (phoneNo ==null){
            LoginUser loginUser = SecurityUtils.getLoginUser();
//            LoginUser loginUser = tokenService.getLoginUser(request);

            if (userService.updateUserAvatar(loginUser.getUsername(), avatar))
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                // 更新缓存用户头像
                loginUser.getUser().setAvatar(avatar);
                tokenService.setLoginUser(loginUser);
                return ajax;
            }
            }
            else {

                if (userService.updateUserAvatar(phoneNo, avatar))
                {
                    return AjaxResult.success();
                }
                return AjaxResult.error("上传图片异常，请联系管理员");

            }
        }
        return AjaxResult.error("上传图片异常，请联系管理员");
    }





    @GetMapping("/logout")
    @ResponseBody
    public AjaxResult logout(HttpServletRequest request) {
        LoginUser loginUser = tokenService.getLoginUser(request);
        if(null != loginUser){
            tokenService.delLoginUser(loginUser.getToken());
        }
        return AjaxResult.success("退出成功！");
    }

}
